package com.mall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.annotation.OperationLog;
import com.mall.db.domain.Category;
import com.mall.db.service.CategoryService;
import com.mall.utils.CategoryJson;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category/cc")
public class CategoryController extends BaseController<Category> {
    @Resource(name = "categoryService")
    private CategoryService cs;

    @Override
    @OperationLog(value = "查询商品类目",type = 0)
    public Map<String, Object> find(Category category) {
        PageHelper.startPage(category.getPage(),category.getLimit());
        QueryWrapper<Category> qw=new QueryWrapper<>();
        if (!StringUtils.isEmpty(category.getId())){
            qw.eq("id",category.getId());
        }
        if (!StringUtils.isEmpty(category.getTitle())){
            qw.eq("title",category.getTitle());
        }
        List<Category> list=cs.list(qw);

        PageInfo<Category> page=new PageInfo<>(list,category.getLimit());
        return this.findMap(page.getList(),page.getTotal());
    }

    @Override
    @OperationLog(value = "新增商品类目",type = 0)
    public Map<String, Object> add(Category category) {
        boolean b=cs.save(category);
        return this.iud("新增",b,category);
    }

    @Override
    @OperationLog(value = "编辑商品类目",type = 0)
    public Map<String, Object> update(Category category) {
        boolean b=cs.updateById(category);
        return this.iud("编辑",b,category);
    }

    @Override
    @OperationLog(value = "删除商品类目",type = 0)
    public Map<String, Object> delete(Category category) {
        QueryWrapper<Category> qw=new QueryWrapper<>();
        qw.eq("id",category.getId());
        boolean b=cs.remove(qw);
        return this.iud("删除",b,category);
    }

    @RequestMapping("/getCategoryJson")
    @ResponseBody
    public JSONArray getCategoryJson(Category category){
        PageHelper.startPage(category.getPage(),category.getLimit());
        QueryWrapper<Category> qw=new QueryWrapper<>();
        List<Category> list=cs.list(qw);
        String menuJson = CategoryJson.getCategoryTree(list);
        return JSON.parseArray(menuJson);
    }
    @RequestMapping("/tree")

    public String tree(Category category){
          List<Category> list = cs.list();

        return CategoryJson.getCategoryTree(list);
    }



}
